package com.msh.automatic.android.control.ui.home

import android.accessibilityservice.AccessibilityService
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.PowerManager
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import cn.hutool.core.date.DateUtil
import com.msh.automatic.android.control.R
import com.msh.automatic.android.control.databinding.FragmentHomeBinding
import com.msh.automatic.android.control.service.AIAccessibilityService
import com.msh.automatic.android.control.service.MqttService
import com.msh.automatic.android.control.task.TaskManager
import com.msh.automatic.android.control.tools.DownloadUtil
import com.msh.automatic.android.control.util.ConfigUtil
import com.msh.automatic.android.control.util.DeviceUtil
import com.msh.automatic.android.control.util.SystemUtil
import com.msh.automatic.android.control.util.api.DeviceApi
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private var homeViewModel: HomeViewModel? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
//        DownloadUtil.download("https://aliyun-oss.meishuhe.cn/test/automatic-android-control-douyin.apk",requireContext())

        Log.d("home","onCreateView")
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
        _binding!!.viewModel = homeViewModel
        binding.lifecycleOwner = viewLifecycleOwner
        val root: View = binding.root
        root.findViewById<TextView>(R.id.MODEL).text=Build.MODEL
        root.findViewById<TextView>(R.id.BRAND).text=Build.BRAND
        root.findViewById<TextView>(R.id.DEVICE).text=Build.DEVICE
        root.findViewById<TextView>(R.id.MANUFACTURER).text=Build.MANUFACTURER
        root.findViewById<TextView>(R.id.RELEASE).text=Build.VERSION.RELEASE
        root.findViewById<TextView>(R.id.SDK_INT).text="${Build.VERSION.SDK_INT}"

        binding.test.setOnClickListener {
//            GlobalScope.launch {
//                var task = EmptyTask(
//                    "https://aliyun-oss.meishuhe.cn/test/automatic-android-control-douyin.apk",
//                    "com.msh.automatic.android.control.douyin",
//                    1,
//                    "美数合抖音智能服务",
//                    "com.msh.automatic.android.control.script.service.AIAccessibilityService"
//                )
//                TaskManager.startTask(task)
//            }

        }
        binding.accessibilityLinearLayout.setOnClickListener {
            if(DeviceUtil.isAccessibilityServiceEnabled(requireContext(),AIAccessibilityService::class.java)){
                homeViewModel?.accessibility?.value = "已开启"
                homeViewModel?.accessibilityColor?.value=binding.textView.currentTextColor
            }else{
                homeViewModel?.accessibility?.value = "未启动.(点击启动)"
                homeViewModel?.accessibilityColor?.value=Color.RED
                DeviceUtil.openAccessibilitySettings(requireContext())

            }
        }
        binding.powerLinearLayout.setOnClickListener {
            if(DeviceUtil.isIgnoringBatteryOptimizations(requireContext())){
                homeViewModel?.power?.value = "已加入"
                homeViewModel?.powerColor?.value=binding.textView.currentTextColor
            }else{
                homeViewModel?.power?.value = "未加入.(点击加入)"
                homeViewModel?.powerColor?.value=Color.RED
                DeviceUtil.requestIgnoreBatteryOptimization(requireContext())
            }
        }

        binding.fileManagerLinearLayout.setOnClickListener {
            if(DeviceUtil.isStoragePermissions()){
                homeViewModel?.fileManager?.value = "已授权"
                homeViewModel?.fileManagerColor?.value=binding.textView.currentTextColor
            }else{
                homeViewModel?.fileManager?.value = "未授权.(点击授权)"
                homeViewModel?.fileManagerColor?.value=Color.RED
                DeviceUtil.requestStoragePermissions(requireContext())
            }
        }
        binding.installApkLinearLayout.setOnClickListener {

            if(DeviceUtil.isInstallApk(requireContext())){
                homeViewModel?.installApk?.value = "已授权"
                homeViewModel?.installApkColor?.value=binding.textView.currentTextColor
            }else{
                homeViewModel?.installApk?.value = "未授权.(点击授权)"
                homeViewModel?.installApkColor?.value=Color.RED
                DeviceUtil.requestInstallApkPermission(requireContext())
            }
        }
        binding.submit.setOnClickListener {
            val clientId = Settings.Secure.getString(requireContext().contentResolver, Settings.Secure.ANDROID_ID)
            GlobalScope.launch{
                val (code,message,body) = DeviceApi.activation(clientId,homeViewModel?.activationCode?.value!!)
                if(code=="SUCCESS"){
                    val data = body!!
                    val token = data.getString("token")!!
                    val expirationTime = data.getDate("expirationTime")!!
                    withContext(Dispatchers.Main) {
                        ConfigUtil.setToken(requireContext(),token)
                        homeViewModel?.inputVisibility?.value=View.GONE
                        homeViewModel?.showVisibility?.value=View.VISIBLE
                        homeViewModel?.expirationDate?.value = DateUtil.formatDate(expirationTime)
                        startMqttService()
                    }
                }else{
                    withContext(Dispatchers.Main) {
                        Toast.makeText(requireContext(),"系统错误：${code} ${message}",Toast.LENGTH_LONG).show()
                    }

                }
            }


        }
        binding.copy.setOnClickListener {
            val token = ConfigUtil.getToken(requireContext())!!
            SystemUtil.copyToClipboard(requireContext(),"label",token)
        }
        return root
    }
    override fun onResume() {
        super.onResume()
        Log.d("home","onResume")
        val clientId = Settings.Secure.getString(requireContext().contentResolver, Settings.Secure.ANDROID_ID)
        GlobalScope.launch{
            val (code,message,body) = DeviceApi.register(clientId)
            if(code=="SUCCESS"){
                val data = body!!
                val token = data.getString("token")
                val expirationTime = data.getDate("expirationTime")
                if(token == null || expirationTime == null || !com.msh.automatic.android.control.util.DateUtil.isDateTodayOrAfter(expirationTime)){
                    ConfigUtil.removetToken(requireContext())
                    withContext(Dispatchers.Main) {
                        homeViewModel?.inputVisibility?.value=View.VISIBLE
                        homeViewModel?.showVisibility?.value=View.GONE
                    }
                }else{
                    withContext(Dispatchers.Main) {
                        homeViewModel?.activationCode?.value=token!!
                        homeViewModel?.expirationDate?.value=DateUtil.formatDate(expirationTime)
                        homeViewModel?.inputVisibility?.value=View.GONE
                        homeViewModel?.showVisibility?.value=View.VISIBLE
                        ConfigUtil.setToken(requireContext(),token)
                        startMqttService()
                    }
                }
            }else{
                Toast.makeText(requireContext(),"系统错误：${code} ${message}",Toast.LENGTH_SHORT).show()
            }
        }

        if(DeviceUtil.isAccessibilityServiceEnabled(requireContext(),AIAccessibilityService::class.java)){
            homeViewModel?.accessibility?.value = "已开启"
            homeViewModel?.accessibilityColor?.value=binding.textView.currentTextColor
        }else{
            homeViewModel?.accessibility?.value = "未启动.(点击启动)"
            homeViewModel?.accessibilityColor?.value=Color.RED
        }

        if(DeviceUtil.isIgnoringBatteryOptimizations(requireContext())){
            homeViewModel?.power?.value = "已加入"
            homeViewModel?.powerColor?.value=binding.textView.currentTextColor
        }else{
            homeViewModel?.power?.value = "未加入.(点击加入)"
            homeViewModel?.powerColor?.value=Color.RED
        }

        if(DeviceUtil.isStoragePermissions()){
            homeViewModel?.fileManager?.value = "已授权"
            homeViewModel?.fileManagerColor?.value=binding.textView.currentTextColor
        }else{
            homeViewModel?.fileManager?.value = "未授权.(点击授权)"
            homeViewModel?.fileManagerColor?.value=Color.RED
        }
        if(DeviceUtil.isInstallApk(requireContext())){
            homeViewModel?.installApk?.value = "已授权"
            homeViewModel?.installApkColor?.value=binding.textView.currentTextColor
        }else{
            homeViewModel?.installApk?.value = "未授权.(点击授权)"
            homeViewModel?.installApkColor?.value=Color.RED
        }
    }

    private fun startMqttService(){
        val jwt = ConfigUtil.getJwt(requireContext())
        if(jwt == null){
            Toast.makeText(requireContext(),"请先激活设备。",Toast.LENGTH_SHORT).show()
            return
        }
        if(homeViewModel?.accessibility?.value != "已开启"){
            Toast.makeText(requireContext(),"请先开启无障碍服务。",Toast.LENGTH_SHORT).show()
            return
        }
        if(homeViewModel?.fileManager?.value != "已授权"){
            Toast.makeText(requireContext(),"请先授权文件管理。",Toast.LENGTH_SHORT).show()
            return
        }
        if(homeViewModel?.installApk?.value != "已授权"){
            Toast.makeText(requireContext(),"请先授权应用安装。",Toast.LENGTH_SHORT).show()
            return
        }
        val intent = Intent(requireContext(), MqttService::class.java)
        ContextCompat.startForegroundService(requireContext(), intent)
    }
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}